package techno.dhr.AsyncTaskDemo;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AsyncTaskDemoActivity extends Activity {

	AsyncTask<String, String, Void> myTask;
	
	RelativeLayout mainLayout;
	ProgressBar mProgressBar;
	LinearLayout mListParent;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mProgressBar = (ProgressBar) findViewById(R.id.progress);
		mListParent = (LinearLayout) findViewById(R.id.ListParent);
	}

	public void showProgressBar(boolean show) {
		if (show) {
			mProgressBar.setVisibility(View.VISIBLE);
		} else {
			mProgressBar.setVisibility(View.INVISIBLE);
		}
	}

	public void startTask(View v) {

		myTask = new AsyncTask<String, String, Void>() {

			String[] splittedString;

			@Override
			protected Void doInBackground(String... params) {

				splittedString = params[0].split(" ");

				for (String currentString : splittedString) {

					if(isCancelled()){
						splittedString = null;
						currentString = null;
						break;
					}else{

						publishProgress(currentString);
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}

				return null;
			}

			protected void onCancelled() {
				showProgressBar(false);
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				showProgressBar(false);
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showProgressBar(true);
			};

			@Override
			protected void onProgressUpdate(String... values) {
				super.onProgressUpdate(values);
				TextView mTextView = new TextView(AsyncTaskDemoActivity.this);
				mTextView.setText(values[0]);
				mListParent.addView(mTextView);
			}

		};

		myTask.execute(new String[] { "This is asyncTask Demo." });
	}

	public void cancelTask(View v) {
		myTask.cancel(true);
	}

}